package com.minshenglife.zanzan.pub.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import net.sf.json.JSONObject;


/**
 * 功能：提供HTTP方面的通用类
 * @author yubaojian0616@163.com
 *
 * mobile enterprise application platform
 * Version 0.1
 */
public class HttpUtil {
	
	/**
	 * 通过post
	 * @param urlStr 访问地址
	 * @param queryString 参数
	 * @return
	 */
	public static String getResultPost(String urlStr) {
		URL url = null;
		HttpURLConnection connection = null;
		try {
			url = new URL(urlStr);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.connect();

//			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
//			out.writeBytes(queryString);
//			out.flush();
//			out.close();

			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			reader.close();
			return buffer.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		return null;
	}
	
	public static String getResultPost(String urlStr,String queryString) {
		try {  
            URL url = new URL(urlStr);// 创建连接  
            HttpURLConnection connection = (HttpURLConnection) url  
                    .openConnection();  
            connection.setDoOutput(true);  
            connection.setDoInput(true);  
            connection.setUseCaches(false);  
            connection.setInstanceFollowRedirects(true);  
            connection.setRequestMethod("POST"); // 设置请求方式  
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式  
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式  
            connection.connect();  
            OutputStreamWriter out = new OutputStreamWriter(  
                    connection.getOutputStream(), "UTF-8"); // utf-8编码  
            out.append(queryString);  
            out.flush();  
            out.close();  
            // 读取响应  
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			reader.close();
			return buffer.toString();
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
		return null;
	}
	
	/**
	 * 通过GET方法获得
	 * @param urlStr
	 * @return
	 */
	public static String getResult(String urlStr){
		assert(ValidateUtil.isNotNull(urlStr));
		URL url = null;
		HttpURLConnection connection = null;
		try {
			url = new URL(urlStr);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("GET");
			connection.setUseCaches(false);
			connection.connect();

			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			reader.close();
			return buffer.toString();
		} catch (IOException e) {
			//e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		return null;
	}
	
	/**
     * 向指定URL发送GET方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
	
	/**
	 * 地址转码
	 * @param str
	 * @param charset
	 * @return
	 */
	public static String getURLEncode(String str,String... charset){
		if(ValidateUtil.isNull(str))return null;
		String result = null;
		try {
			result = java.net.URLEncoder.encode(str, ValidateUtil.isNullArray(charset)?"UTF-8":charset[0]);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 地址转码
	 * @param str
	 * @param charset
	 * @return
	 */
	public static String getURLDecode(String str,String... charset){
		if(ValidateUtil.isNull(str))return null;
		String result = null;
		try {
			result = java.net.URLDecoder.decode(str, ValidateUtil.isNullArray(charset)?"UTF-8":charset[0]);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	
	/** 
     * 发起https请求并获取结果 
     *  
     * @param requestUrl 请求地址 
     * @param requestMethod 请求方式（GET、POST） 
     * @param outputStr 提交的数据 
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值) 
     */  
	 public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {  
   	  JSONObject jsonObject = null;  
         StringBuffer buffer = new StringBuffer();  
         try { 
             // 创建SSLContext对象，并使用我们指定的信任管理器初始化  
             TrustManager[] tm = { new MyX509TrustManager() };  
             SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");  
             sslContext.init(null, tm, new java.security.SecureRandom());  
             // 从上述SSLContext对象中得到SSLSocketFactory对象  
             SSLSocketFactory ssf = sslContext.getSocketFactory();  
             URL url = new URL(null,requestUrl,new sun.net.www.protocol.https.Handler());  
             HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();  
             httpUrlConn.setSSLSocketFactory(ssf);  
   
             httpUrlConn.setDoOutput(true);  
             httpUrlConn.setDoInput(true);  
             httpUrlConn.setUseCaches(false);  
             // 设置请求方式（GET/POST）  
             httpUrlConn.setRequestMethod(requestMethod);  
//             if ("GET".equalsIgnoreCase(requestMethod))  
                 httpUrlConn.connect();  
   
             // 当有数据需要提交时  
             if (null != outputStr && !("".equals(outputStr))) {  
                 OutputStream outputStream = httpUrlConn.getOutputStream();  
                 // 注意编码格式，防止中文乱码  
                 outputStream.write(outputStr.getBytes("UTF-8"));  
                 outputStream.close();  
             }  
   
             // 将返回的输入流转换成字符串  
             InputStream inputStream = httpUrlConn.getInputStream();
             InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); 
             BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
   
             String str = null;  
             while ((str = bufferedReader.readLine()) != null) {  
                 buffer.append(str);  
                 System.out.println(str);
             }  
             bufferedReader.close();  
             inputStreamReader.close();  
             // 释放资源  
             inputStream.close();  
             inputStream = null;  
             httpUrlConn.disconnect();  
             jsonObject = JSONObject.fromObject(buffer.toString());  
         } catch (ConnectException ce) { 
       	  ce.printStackTrace();
         } catch (Exception e) {
       	  e.printStackTrace();
         }  
         return jsonObject;    
   }   
	 
	 public static String httpsRequestString(String requestUrl, String requestMethod, String outputStr) {  
		 JSONObject jsonObject = null;  
		 StringBuffer buffer = new StringBuffer();  
		 try { 
			 // 创建SSLContext对象，并使用我们指定的信任管理器初始化  
			 TrustManager[] tm = { new MyX509TrustManager() };  
			 SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");  
			 sslContext.init(null, tm, new java.security.SecureRandom());  
			 // 从上述SSLContext对象中得到SSLSocketFactory对象  
			 SSLSocketFactory ssf = sslContext.getSocketFactory();  
			 URL url = new URL(null,requestUrl,new sun.net.www.protocol.https.Handler());  
			 HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();  
			 httpUrlConn.setSSLSocketFactory(ssf);  
			 
			 httpUrlConn.setDoOutput(true);  
			 httpUrlConn.setDoInput(true);  
			 httpUrlConn.setUseCaches(false);  
			 // 设置请求方式（GET/POST）  
			 httpUrlConn.setRequestMethod(requestMethod);  
//             if ("GET".equalsIgnoreCase(requestMethod))  
			 httpUrlConn.connect();  
			 
			 // 当有数据需要提交时  
			 if (null != outputStr) {  
				 OutputStream outputStream = httpUrlConn.getOutputStream();  
				 // 注意编码格式，防止中文乱码  
				 outputStream.write(outputStr.getBytes("UTF-8"));  
				 outputStream.close();  
			 }  
			 
			 // 将返回的输入流转换成字符串  
			 InputStream inputStream = httpUrlConn.getInputStream();
			 InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); 
			 BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
			 
			 String str = null;  
			 while ((str = bufferedReader.readLine()) != null) {  
				 buffer.append(str);  
				 System.out.println(str);
			 }  
			 bufferedReader.close();  
			 inputStreamReader.close();  
			 // 释放资源  
			 inputStream.close();  
			 inputStream = null;  
			 httpUrlConn.disconnect();  
		 } catch (ConnectException ce) { 
			 ce.printStackTrace();
		 } catch (Exception e) {
			 e.printStackTrace();
		 }  
		 return buffer.toString();    
	 }   
	 
	 //‘url’：是‘?’之前的部分不包含问号。
	 public static String uploadPicture(File img, String accessToken, String url) {
		 String imgURL = null;
		 DataInputStream in = null;
		 BufferedReader in2 = null;
		 DataOutputStream out = null;
		 URL destURL = null;
		 HttpsURLConnection connc = null;
		 
		 try {
			 String imgName = img.getPath().substring(img.getPath().lastIndexOf("\\") + 1, img.getPath().length());
			 String boundary = "****";
			 StringBuffer jsonStr = new StringBuffer();
			 byte[] tempData = new byte[2045];
			 int len = 0;
			 String tempStr = null;
			 JSONObject json = null;
			 
			 destURL = new URL(url + "?access_token=" + accessToken);
			 connc = (HttpsURLConnection) destURL.openConnection();
			 connc.setDoInput(true);
			 connc.setDoOutput(true);
			 connc.setUseCaches(false);
//			 connc.setInstanceFollowRedirects(true);
			 connc.setRequestProperty("charset", "utf-8");
			 connc.setRequestMethod("POST");
			 connc.setRequestProperty("Accept", "application/json");
			 connc.setRequestProperty("Connection", "Keep-Alive");
			 connc.setRequestProperty("Content-Type",
						"multipart/form-data;boundary=" + boundary);
	         connc.connect();
			 in = new DataInputStream(new FileInputStream(img));
			 out = new DataOutputStream(connc.getOutputStream());
			 
			 out.writeBytes("--" + boundary + "\r\n");
			 out.writeBytes("Content-Disposition:form-data;name=\"" + img +"\";filename=\"" + imgName + 
					 "\";filelength=\"" + img.getPath() + "\";Content-Type=\"" + ".jpg" + "\"" + "\r\n");
			 out.writeBytes("Content-Type:image/jpg\r\n");
			 out.writeBytes("\r\n");
			 
			 while((len = in.read(tempData)) != -1) {
				 out.write(tempData, 0, len - 1);
			 }
			 
			 out.writeBytes("\r\n");
			 out.writeBytes("--" + boundary + "\r\n");
			 out.flush();
			 out.close();
			 in2 = new BufferedReader(new InputStreamReader(connc.getInputStream(), "utf-8"));
			 
			 while((tempStr = in2.readLine()) != null) {
				 if(tempStr.length() > 0) {
					 jsonStr.append(tempStr);
				 }
			 }
			 
			 
			 
			 json = JSONObject.fromObject(jsonStr.toString());
			 
			 if(json.containsKey("url"))
				 imgURL = json.getString("url");
			 
		 } catch(Throwable e) {
			 e.printStackTrace();
		 } finally {
			 
			 try {
				 
				 if(in != null) {
					 in.close();
				 }
				 
				 if(in2 != null) in2.close();
				 
				 if(out != null) {out.flush(); out.close();}
				 
			 } catch(Throwable e) {
				 e.printStackTrace();
			 }
			 
		 }
		 
		 return imgURL;
	 }
	 
	 public static void main(String[] args) {
//		 try {
//			 if(1==2){
//				 throw new NullPointerException();
//			 }
//			 throw new Throwable();
//		} catch (NullPointerException e) {
//			e.printStackTrace();
//		} catch (Throwable e) {
//			e.printStackTrace();
//		}
		 String a = "{\"openId\": \"11\",\"orderId\": \"12\",\"orderNum\": \"13\",\"flag\": \"0\",\"trackingNum\": \"运单号\",\"trackcompany\":\"物流公司\"}";
		 System.out.println(getResultPost("http://localhost:8080/mslife_wx/flyingStart/applyState.json",a));
	}
}
